package cn.sczhyt.common.utils;

import cn.sczhyt.common.exception.RRException;
import cn.sczhyt.modules.szhy.entity.MeetingMobileAppEntity;
import net.dongliu.apk.parser.bean.ApkMeta;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.RequestContext;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;
import net.dongliu.apk.parser.ApkFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;

/**
 * 创建者  罗世杰
 * 创建日期 2020/6/30
 * 描述  附件文件上传工具类
 *
 * @author Admin
 */
@Component
public class UploadFileUtils {


    private static String imagePath;
    private static String filePath;
    private static String apkPath;
    private static String imageServerPath;
    private static String apkServerPath;

    /**
     * 图片配置
     * @param imagePath
     */
    @Value("${cn.sczhyt.szhy.image.upload-path}")
    public  void setImagePath(String imagePath){
        UploadFileUtils.imagePath = imagePath;
    }

    /**
     * 文件配置
     */
    @Value("${cn.sczhyt.szhy.file.upload-path}")
    public  void setFilePath(String filePath){
        UploadFileUtils.filePath = filePath;
    }

    /**
     * 安装包路径配置
     * @param apkPath
     */
    @Value("${cn.sczhyt.szhy.apk.upload-path}")
    public  void setApkPath(String apkPath){
        UploadFileUtils.apkPath = apkPath;
    }

    /**
     * 服务器安装包路径配置
     * @param apkServerPath
     */
    @Value("${cn.sczhyt.szhy.apk.server-path}")
    public  void setApkServerPath(String apkServerPath){
        UploadFileUtils.apkServerPath = apkServerPath;
    }
    /**
     * 服务器图片路径配置
     * @param imageServerPath
     */
    @Value("${cn.sczhyt.szhy.image.server-path}")
    public  void setImageServerPath(String imageServerPath){
        UploadFileUtils.imageServerPath = imageServerPath;
    }

    /**
     * 图片上传
     * @param file
     * @return
     */
    public static R imageSave(MultipartFile file){

        //根据时间创建文件夹
        String dateFile = DateUtils.format(new Date(), "yyyyMMddHHmmssSSSS");

        String realPath = imagePath;

        System.out.println( "真实路径" + realPath);
        File path = new File(realPath);

        if (!path.exists()) {
            path.mkdirs();
        }

        //保存文件
        if (!file.isEmpty()) {
            try {
                JSONObject jsonObject = new JSONObject();

                String originalFilename = file.getOriginalFilename();
                //文件存储位置
                String filepath = realPath +"/" + dateFile + originalFilename;

                System.out.println(filepath);

                file.transferTo(new File(filepath));
                //修改权限
                Runtime.getRuntime().exec("chmod 755 " + imagePath + dateFile + originalFilename);

                //上传成功后对路径及文件名进行处理
                jsonObject.put("name", originalFilename);
                jsonObject.put("url", imageServerPath + dateFile + originalFilename);
                System.out.println(jsonObject);
                return R.ok().put("data",jsonObject);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return R.error(2005,"上传文件为空！");
    }




    /**
     * app安装包上传工具
     *
     * @param file
     * @return
     */
    public static R appSave(MultipartFile file) {

        //根据时间创建文件名
        String dateString = DateUtils.format(new Date(), "yyyyMMddHHmmssSSSS");
        //项目的resources下的路径
        String realPath = apkPath;
        File path = new File(realPath);
        System.out.println( "查看路径" + realPath);
        if (!path.exists()) {
            path.mkdirs();
        }

        //上传成功后对路径及文件名进行处理
        MeetingMobileAppEntity appEntity = new MeetingMobileAppEntity();
        //保存文件
        if (file.isEmpty()) {
            throw new RRException("上传文件为空", 510);
        }
        try {
            //转存文件 file.getOriginalFilename();文件原名称包括后缀名
            String originalFilename = file.getOriginalFilename();

            if (originalFilename.endsWith(".apk") != true) {
                throw new RRException("暂时只支持安卓上传升级包", 512);
            }
            //临时文件保存地址
            String tmpPath = realPath + "tmp\\" + dateString + originalFilename;
            //临时文件保存
            file.transferTo(new File(tmpPath));


            System.out.println(tmpPath);
            //Apk解析工具
            ApkFile apkFile = new ApkFile(new File(tmpPath));
            ApkMeta apkMeta = apkFile.getApkMeta();
            String versionName = apkMeta.getVersionName();
            String versionCode = apkMeta.getVersionCode().toString();
            String packageName = apkMeta.getPackageName() + ".apk";

            //文件保存地址
            String savePath = realPath + apkMeta.getPackageName() + "_" + versionName + "_" + dateString + ".apk";

            System.out.println(savePath);

            //文件移动
            FileCopyUtils.copy(new File(tmpPath), new File(savePath));

            //修改权限
            Runtime.getRuntime().exec("chmod 755 " + savePath);

            //删除临时文件
            new File(tmpPath).delete();

            //包名
            appEntity.setPackageName(packageName);
            //包大小KB
            appEntity.setTotalSizeKb(new BigDecimal(file.getSize() / 1024).setScale(2, BigDecimal.ROUND_HALF_UP));
            //文件地址
            appEntity.setRealPath( apkServerPath + apkMeta.getPackageName()  + "_" + versionName + "_" + dateString + ".apk");
            //版本名称
            appEntity.setVersionName(versionName);
            //版本代码
            appEntity.setVersionCode(versionCode);
            //app类型
            appEntity.setType("Android");

        } catch (IOException e) {
            e.printStackTrace();
            return R.error(509, "该安装包已存在，请勿重新上传");
        }
        System.out.println("UploadFileUtils.appSave" + appEntity);

        return R.ok().put("data", appEntity);
    }
    /**
     * 创建者  罗世杰
     * 创建日期 2020/9/11
     * 描述  数字会议文件上传工具
     */
    public static String szhyFileSave( MultipartFile[] files, HttpServletRequest request, HttpServletResponse response){

        //根据时间创建文件夹
        Date date = new Date();
        String dateFile = DateUtils.format(date, "yyyyMMdd");
        //根据时间创建文件名
        String filename = UUIDUtils.getUUID();
        //项目的resources下的路径
//        String realPath = ResourceUtils.getURL("classpath:").getPath() + "static/" + "file/";
        String realPath = filePath;
        System.out.println( "查看路径" + realPath);
        File path = new File(realPath);

        JSONArray jsonArray = new JSONArray();

        if (!path.exists()) {
            path.mkdirs();
        }
        //判断file数组不能为空并且长度大于0
        if (files != null && files.length > 0) {
            //循环获取file数组中得文件
            for (int i = 0; i < files.length; i++) {
                MultipartFile file = files[i];
                //保存文件
                if (!file.isEmpty()) {
                    try {
                        JSONObject jsonObject = new JSONObject();
                        //转存文件 file.getOriginalFilename();文件原名称包括后缀名
                        String originalFilename = file.getOriginalFilename();
                        //原文件名的后缀名
                        String substring = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
                        //文件存储位置
                        String filepath = realPath + filename + "-" + i + "." + substring;
                        System.out.println(filepath);
                        file.transferTo(new File(filepath));
                        //上传成功后对路径及文件名进行处理
                        jsonObject.put("name", originalFilename);
                        jsonObject.put("url", realPath + filename + "-" + i + "." + substring);
                        jsonArray.add(i, jsonObject);
                    } catch (IOException e) {
                        e.printStackTrace();
                        return null;
                    }
                }
            }
        }
        System.out.println(jsonArray);
        return jsonArray.toString();
    }
}
